package com.hxzy.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hxzy.yygh.common.exception.YyghException;
import com.hxzy.yygh.common.result.ResultCodeEnum;
import com.hxzy.yygh.hosp.repository.ScheduleRepository;
import com.hxzy.yygh.hosp.service.DepartmentService;
import com.hxzy.yygh.hosp.service.HospitalService;
import com.hxzy.yygh.hosp.service.ScheduleService;
import com.hxzy.yygh.model.hosp.BookingRule;
import com.hxzy.yygh.model.hosp.Department;
import com.hxzy.yygh.model.hosp.Hospital;
import com.hxzy.yygh.model.hosp.Schedule;
import com.hxzy.yygh.vo.hosp.BookingScheduleRuleVo;
import com.hxzy.yygh.vo.hosp.ScheduleOrderVo;
import com.hxzy.yygh.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public void saveSchedule(Map<String, Object> paramMap) {
        //把map集合转换为实体类对象
        String jsonString = JSON.toJSONString(paramMap);
        Schedule schedule = JSON.parseObject(jsonString, Schedule.class);

        //从map集合中获取参数
        String hoscode = schedule.getHoscode();
        String scheduleId = schedule.getHosScheduleId();

        //根据医院编号和科室编号，查询mongoDB数据中，是否存在此数据
        Schedule scheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode,scheduleId);

        //判断该数据在数据库中是否存在
        if (scheduleExist == null){
            //执行新增操作
            //封装运维字段
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            //执行新增方法
            scheduleRepository.save(schedule);
        }else{
            //执行修改操作
            //封装运维字段
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(scheduleExist.getIsDeleted());
            //执行修改方法
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> findPageDepartment(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        //1.封装pageAble参数
        Pageable pageAble = PageRequest.of(page - 1, limit);

        //2.封装Department对象
        Schedule schedule = new Schedule();
        //属性拷贝
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        //属性赋值
        schedule.setIsDeleted(0);

        //2.封装matcher对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        //4.封装example对象参数
        Example<Schedule> example = Example.of(schedule, matcher);

        //5.执行查询全部方法并返回
        return scheduleRepository.findAll(example, pageAble);
    }


    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    //查询排班数据实现类
    @Override
    public Map<String, Object> getScheduleList(Integer page, Integer limit, String hoscode, String depcode) {
        //1. 构造查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2. 查询排班规则数据
        //构造聚合管道--排班规则数据
        Aggregation agg = Aggregation.newAggregation(
                //匹配查询条件
                Aggregation.match(criteria),
                //分组
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),

                //分页
                Aggregation.skip((page-1)*limit),//开始位置
                Aggregation.limit(limit)//每页记录数
        );
        //执行聚合操作--排班规则数据
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        //返回排班结果数据--排班规则数据
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregate.getMappedResults();

        //3. 分组查询的总记录数
        //构造聚合管道--分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        //执行聚合操作--分组查询的总记录数
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        //返回排班结果数据--分组查询的总记录数
        int total = totalAggResults.getMappedResults().size();

        //4. 转换日期格式------具体的星期X
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //5. 获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        Map<String,String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);

        //6. 封装返回数据
        Map<String,Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        result.put("total", total);
        result.put("baseMap", baseMap);

        //7. 返回最终数据
        return result;
    }

    //查询对应日期的具体排班信息
    @Override
    public List<Schedule> getDetailsSchedule(String hoscode, String depcode, String workDate) {
        //根据医院编号、科室编号、日期查询排班信息
        List<Schedule> scheduleList =
                scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());

        //补充数据--医院名称、科室名称、日期名称
        scheduleList.forEach(item->{
            this.packageSchedule(item);
        });

        //返回当天具体排班数据
        return scheduleList;
    }

    //获得当前科室的可预约排班数据
    @Override
    public Map<String, Object> getBookingScheduleRule(int page, int limit, String hoscode, String depcode) {
        //返回数据集合
        Map<String, Object> result = new HashMap<>();

        //获取医院数据
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (hospital == null){
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        //从医院信息中,获取医院规则数据
        BookingRule bookingRule = hospital.getBookingRule();

        //获取可预约的日期的数据(分页展示)
        IPage<Date> datePage = this.getListDate(page, limit, bookingRule);

        //从分页对象中，获取当前可预约的日期集合数据
        List<Date> dateList = datePage.getRecords();

        //获取可预约日期里，每一个日期下对应的可预约数集合
            //构造条件
            Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
            //构造聚合管道
            Aggregation agg = Aggregation.newAggregation(
                    Aggregation.match(criteria),//匹配条件
                    Aggregation.group("workDate").first("workDate").as("workDate")//分组
                            .count().as("docCount")//计数
                            .sum("availableNumber").as("availableNumber")//可预约数量
                            .sum("reservedNumber").as("reservedNumber")//剩余预约数

            );

            //执行聚合操作
            AggregationResults<BookingScheduleRuleVo> aggregateResult = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

            //从聚合对象中，取出可预约日期里，对应的预约数集合
            List<BookingScheduleRuleVo> scheduleRuleVoList = aggregateResult.getMappedResults();



        //将每一个日期下对应的 可预约数量 集合，转换为一个map集合,key为日期，value为可预约数对象
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleRuleVoList)){
            scheduleVoMap = scheduleRuleVoList.stream()
                    .collect(
                            Collectors.toMap(
                                    BookingScheduleRuleVo::getWorkDate,//key
                                    BookingScheduleRuleVo -> BookingScheduleRuleVo//value
                            )
                    );
        }

        //排班对象集合，相当于map的vue集合
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();

        //封装mao集合的剩余数量相关属性
        for (int i = 0; i < dateList.size(); i++) {
            //得到map集合中的 key
            Date date = dateList.get(i);
            //根据key，从map集合中获取到排班对象
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            //若排班对象是否为空
            if(bookingScheduleRuleVo == null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //设置就诊医生人数 为0
                bookingScheduleRuleVo.setDocCount(0);
                //设置剩余挂号数量 为-1
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //若排班对象是否不为空
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);

            //封装dayOfWeek属性,表示当前日期对应周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //封装预约状态-status( 0：正常  |  1：即将放号  | -1：当天已停止挂号)
                //最后一页的最后一条显示 即将预约
                if (i == dateList.size() - 1 && page == datePage.getPages()){
                    //设置即将放号
                    bookingScheduleRuleVo.setStatus(1);
                }else {
                    bookingScheduleRuleVo.setStatus(0);
                }

            //如果过了预约截至时间，不能预约
                if (i == 0 && page == 1){
                    DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                    if (stopTime.isBeforeNow()){
                        //设置停止挂号
                        bookingScheduleRuleVo.setStatus(-1);
                    }
                }

            //将排班对象加入临时排班对象集合
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //将排班集合对象放入返回数据集中
        result.put("bookingScheduleRuleVoList",bookingScheduleRuleVoList);

        //将中记录数放入返回数据集中
        result.put("total", datePage.getTotal());

        //其他基础科室数据封装
        Map<String, String> baseMap = new HashMap<>();
            //医院名称
            baseMap.put("hosname", hospitalService.getHospName(hoscode));
            //根据医院编号、科室编号,获取科室对象
            Department department =departmentService.getDepartment(hoscode, depcode);
            //大科室名称
            baseMap.put("bigname", department.getBigname());
            //科室名称
            baseMap.put("depname", department.getDepname());

            //月
            baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));

            //放号时间
            baseMap.put("releaseTime", bookingRule.getReleaseTime());

            //停号时间
            baseMap.put("stopTime", bookingRule.getStopTime());

        //将中 其他基础科室数据集合 放入返回数据集中
        result.put("baseMap", baseMap);
        return result;
    }

    //根据排班id获取排班数据
    @Override
    public Schedule getScheduleById(String scheduleId) {
        //查询mongoDB
        Optional<Schedule> optional = scheduleRepository.findById(scheduleId);
        Schedule schedule = new Schedule();
        if (optional.isPresent()){
            schedule = optional.get();
        }
        //包装参数
        this.packageSchedule(schedule);
        //返回对象
        return schedule;
    }

    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //创建返回集合
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();

        //获取排班信息
        Schedule schedule = new Schedule();
        Optional<Schedule> optional = scheduleRepository.findById(scheduleId);
        if (optional.isPresent()){
             schedule = optional.get();
        }

        //获取预约规则信息
            //1.根据排班信息中的医院编号,获取医院信息
            Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
            if (hospital == null){
                throw new YyghException(ResultCodeEnum.PARAM_ERROR);
            }

            //2.根据医院信息获取预约规则信息
            BookingRule bookingRule = hospital.getBookingRule();
            if (bookingRule == null){
                throw new YyghException(ResultCodeEnum.PARAM_ERROR);
            }

        //封装对象属性
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    //更新排班信息(整合mq)
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    //根据排班编号查询排班信息
    @Override
    public Schedule getScheduleMsg(String scheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHosScheduleId(scheduleId);
        this.packageSchedule(schedule);
        return schedule;
    }

    //获取可预约的日期的数据(分页展示)
    private IPage<Date> getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //预约周期
        int cycle = bookingRule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if(releaseTime.isBeforeNow()) cycle += 1;
        //可预约所有日期，最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
        //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page-1)*limit;
        int end = (page-1)*limit+limit;
        if(end >dateList.size()) end = dateList.size();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;

    }

    //将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    //封装医院名称、科室名称、日期名称到schedule对象
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname", hospitalService.getHospName(schedule.getHoscode()));

        //设置科室名称
        schedule.getParam().put("depname", departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));

        //设置日期
        schedule.getParam().put("dayOfWeek", getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    //根据日期获取周几数据
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }



}
